package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.business.wechat.service.WeixinService;
import com.fanrenqiji.modules.sys.entity.Office;
import com.fanrenqiji.modules.sys.entity.Role;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.service.OfficeService;
import com.fanrenqiji.modules.sys.service.SystemService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月9日 下午5:16:00
 * @description 通路的相关视图解析，
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office/")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;
	
	@Autowired
	private SystemService systemService;

	@Autowired
	private WeixinService wxService;

	@ModelAttribute(value = "office")
	public Office getOffice(@RequestParam(required = false) Long id) {
		if (id != null) {
			return officeService.findById(id);
		} else {
			return new Office();
		}
	}

	/**
	 * 机构列表（树结构）
	 * 
	 * @param model
	 * @param office
	 * @return
	 */
	@RequestMapping(value = { "list", "" })
	@RequiresPermissions(value = "sys:office:view")
	public String treeList(Model model, Office office) {
		User user = UserUtils.getUser();
		if (user.isAdmin()) {
			office.setId(1L);
		} else {
			office.setId(user.getOffice().getId());
		}
		model.addAttribute("office", office);
		List<Office> list = Lists.newArrayList();
		List<Office> sourcelist = officeService.findAll();
		Office.sortList(list, sourcelist, office.getId());
		model.addAttribute("list", list);
		return "modules/sys/officeList";
	}
	
	
	/**
	 * 机构列表 普通列表
	 * 
	 * @param model
	 * @param office
	 * @return
	 */
	@RequestMapping(value = "commonList")
	@RequiresPermissions(value = "sys:office:view")
	public String commonList(Office office ,Model model,
			@RequestParam(defaultValue = "1",required=false) Long parentId,
			HttpServletRequest request, HttpServletResponse response) {
		
		//是否负责人角色
		boolean isCompPrincipal =false;
		
		User user = UserUtils.getUser();
		
		if(user.isAdmin()){
			isCompPrincipal = true;
		}else{
			// 用户角色为 公司负责人compPrincipal的用户
			for (Role role : user.getRoleList()) {
				if ("compPrincipal".equals(role.getEnName())) {
					isCompPrincipal = true;
					break;
				}
			}
		}
		
		Page<Office> officePage = officeService
				.findPage(new Page<Office>(
						request, response), office,parentId);
		
		model.addAttribute("page", officePage);
		
		model.addAttribute("parentId", parentId);
		
		model.addAttribute("isCompPrincipal", isCompPrincipal);
		
		return "modules/sys/officeCommonList";
	}
	

	/**
	 * 添加和修改机构视图
	 * 
	 * @param office
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model) {
		User user = UserUtils.getUser();
		if (office.getParent() == null || office.getParent().getId() == null) {
			office.setParent(user.getOffice());
		}
		office.setParent(officeService.findById(office.getParent().getId()));
		if (office.getArea() == null) {
			office.setArea(user.getOffice().getArea());
		}
		model.addAttribute("office", office);
		model.addAttribute("currentOffice", UserUtils.getUser().getOffice());
		return "modules/sys/officeForm";
	}
	
	
	
	/**
	 * 普通列表结构 添加和修改机构视图
	 * 
	 * @param office
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "commonForm")
	public String commonForm(Office office, Model model) {
		User user = UserUtils.getUser();
		if (office.getParent() == null || office.getParent().getId() == null) {
			office.setParent(user.getOffice());
		}
		office.setParent(officeService.findById(office.getParent().getId()));
		if (office.getArea() == null) {
			office.setArea(user.getOffice().getArea());
		}
		model.addAttribute("office", office);
		model.addAttribute("currentOffice", UserUtils.getUser().getOffice());
		return "modules/sys/officeCommonForm";
	}
	
	
	
	
	/**
	 * 
	 * @param loginName  用户登录名
	 * @param name    用户姓名
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "view")
	public String view(
			String loginName,
			String name,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response) {
		
		String id = request.getParameter("id");
		Office	office =officeService.findById(new Long(id));
		model.addAttribute("office", office);
		
		User user = new User();
		user.setLoginName(loginName);
		user.setName(name);
		user.setOffice(office);
		Page<User> userPage = systemService.findOfficeBelowUserByPage(new Page<User>(
				request, response), user);
		model.addAttribute("page", userPage);
		
		/*List<Role> roleList =systemService.findAllRole();
		model.addAttribute("roleList", roleList);*/
		return "modules/sys/officeView";
	}


	/**
	 * 添加和修改机构
	 * 
	 * @param office
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "save")
	public String save(Office office, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, office)) {
			return form(office, model);
		}
		officeService.save(office);
		addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/office/";
	}
	
	
	/**
	 * 平行结构列表对应的编辑方法，添加和修改机构
	 * 
	 * @param office
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "saveCommon")
	public String saveCommon(Office office, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, office)) {
			return form(office, model);
		}
		
		office.setParent(officeService.findById(office.getParent().getId()));
		Long parentId =office.getParent().getId();
		if(office.getParent().getGrade()!=null){
			
			int parentGrade =  Integer.valueOf(office.getParent().getGrade());
			//父级机构的级别为4级就不在允许添加 :4级的序号为5
			if(parentGrade>=5){
				addMessage(redirectAttributes, "提示：父级机构["+office.getParent().getName()+"]级别已是4级，系统暂不支持添加下级机构!");
				parentId = office.getParent().getParent().getId();
			}else{
				
				officeService.saveCommon(office);
				addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
			}
		}
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/office/commonList?repage&parentId="+parentId;
	}

	

	/**
	 * 删除机构
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		if (Office.isRoot(id)) {
			addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
		} else {
			officeService.delete(id);
			addMessage(redirectAttributes, "删除机构成功");
		}
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/office/";
	}

	/**
	 * 获得机构树
	 * 
	 * @param extId
	 * @param type
	 * @param grade
	 * @param response
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(
			@RequestParam(required = false) Long extId,
			@RequestParam(required = false) Long type,
			@RequestParam(required = false) Long grade,
			HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findAll();
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((extId == null || (extId != null && !extId.equals(e.getId()) && e
					.getParentIds().indexOf("," + extId + ",") == -1))
					&& (type == null || (type != null && Integer.parseInt(e
							.getOfficeType()) <= type.intValue()))
					&& (grade == null || (grade != null && Integer.parseInt(e
							.getGrade()) <= grade.intValue()))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParent() != null ? e.getParent().getId(): 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	/**
	 * 校验机构编码是否已经存在
	 * @param oldCode
	 * @param code
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "checkCode")
	public String checkCode(String oldCode, String code) {
		if (code!=null && code.equals(oldCode)) {
			return "true";
		} else if (code!=null && officeService.findByCode(code) == null) {
			return "true";
		}
		return "false";
	}
	
	
	/**
	 * 通过机构ID获取机构级别
	 * 
	 * @param getOfficeGradeById
	 *            品牌ID
	 * @return
	 */
	@RequestMapping(value = "getOfficeGradeById", method = RequestMethod.GET, headers = { "Accept=application/json" })
	public @ResponseBody String getOfficeGradeById(
			@RequestParam(value = "officeId") Long officeId) {
	
		return  officeService.getOfficeGradeById(officeId);
	
	}


	/**
	 * 生成相应公司的二维码
	 * @param response
	 */
	@RequestMapping(value = "qr", method = RequestMethod.GET)
	public void getQRCode(HttpServletResponse response,String id ) {
		System.out.println(id);
		try {
			WxMpQrCodeTicket ticket = wxService.getQrcodeService().qrCodeCreateLastTicket("fanrenqiji_wx_teacher_1_"+id);
			String url = wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket());
			System.out.println(url);
			response.getWriter().write(url);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
